<template>
  <el-switch
    v-tippy
    content="开启自定义"
    v-model="custom"
    class="mr-1"
  />
  <el-input-number
    v-if="custom"
    v-tippy
    content="字体大小"
    v-model="fontSize"
    :min="0"
    size="small"
    controls-position="right"
    class="w-[90px]"
  />
  <el-select
    v-if="custom"
    v-model="fontUnit"
    size="small"
    class="w-[50px]"
  >
    <el-option label="px" value="px"></el-option>
    <el-option label="pt" value="pt"></el-option>
    <el-option label="em" value="em"></el-option>
    <el-option label="rem" value="rem"></el-option>
  </el-select>
</template>

<script setup>
import {ref, reactive, computed, watch, onMounted, toRefs} from 'vue'

const units = [ 'px', 'pt', 'em', 'rem' ]
const modelValue = defineModel()
// 定义 props
const props = defineProps({
  eleDef: {
    type: Object,
    default: null
  },
  currentItemElCode: {
    type: String,
    default: ''
  }
})

// 定义 emits
const emit = defineEmits(['change'])

// 状态
const {
  innerValue,
  fontSize,
  fontUnit,
  custom,
  parsing
} = toRefs(reactive({
  innerValue: '',
  fontSize: 14,
  fontUnit: 'px',
  custom: false,
  parsing: false
}))

// 生命周期钩子
onMounted(() => {
  if (modelValue.value) innerValue.value = modelValue.value
})

// Watchers
watch(
  () => modelValue.value,
  (val) => {
    if(val) {
      parseValue(val)
      custom.value = true;
    } else {
      custom.value = false
    }
  },
  { deep: true }
)

watch(
  () => [fontSize.value, fontUnit.value],
  () => {
    setValue()
  }
)

watch(
  () => custom.value,
  (val) => {
    if (val && !modelValue.value) {
      const name = props.currentItemElCode || props.eleDef?._code
      if (name) {
        const nodes = document.getElementsByName(name)
        const ele = nodes?.[0]

        if (ele) {
          const computedStyle = window.getComputedStyle(ele)
          const fontSizeStr = computedStyle.getPropertyValue('font-size')
          parseValue(fontSizeStr)
        }
      }
    }
    setValue()
  }
)

// 方法实现
/*const willReceiveProps = (newVal) => {
  if (!$utils.deepEquals(newVal, innerValue.value)) {
    innerValue.value = newVal
  }
}*/

const parseValue = (fontSizeStr) => {
  // parsing.value = true
  if (fontSizeStr) {
    const size = parseInt(fontSizeStr)
    const unit = fontSizeStr.substr(-2)

    if (size && size > 0) {
      fontSize.value = size
      if (units.includes(unit)) fontUnit.value = unit
    }
  }
}
const setValue = () => {
  let val = ''

  if (parsing.value) return
  if (custom.value) {
    val = `${fontSize.value}${fontUnit.value}`
  } else {
    val = ''
  }

  modelValue.value = val
}
</script>
